package com.donger.business.upms.controller;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.donger.auth.component.UserDetail;
import com.donger.auth.utils.SecurityUtils;
import com.donger.business.upms.dto.UserDto;
import com.donger.business.upms.dto.UserForm;
import com.donger.business.upms.dto.UserInfo;
import com.donger.business.upms.entity.SysUser;
import com.donger.business.upms.query.UserQuery;
import com.donger.business.upms.service.ISysUserService;
import com.donger.business.upms.vo.UserVo;
import com.donger.common.core.utils.Res;
import com.donger.common.core.utils.Result;
import com.donger.common.data.entity.DropDown;
import com.donger.common.query.enums.CommonQuery;
import com.donger.common.query.utils.QueryGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统用户 前端控制器 基本完成
 * </p>
 * <p>
 * 用户表增加 别名 user
 *
 * @author 7326
 */
@AllArgsConstructor
@RestController
@RequestMapping("/sys/user")
@Api(tags = "用户模块提供API")
public class SysUserController {

    private static final String MODULE_NAME = "系统用户管理";
    private static final Long SUPER_ADMIN = 1L;
    private final ISysUserService sysUserService;

    /**
     * 所有用户列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "分页查询用户")
    public Result list(Page<UserVo> page, UserQuery userQuery) {
        QueryWrapper<SysUser> objectQueryWrapper = QueryGenerator.initQueryWrapper(userQuery);
        return Res.ok(sysUserService.getUserWithRolePage(page, objectQueryWrapper));
    }

    /**
     * 高级查询
     *
     * @param page
     * @param userQuery
     * @param commonQuery
     * @return
     */
    @GetMapping("/queryPageList")
    @ApiOperation(value = "高级分页查询用户列表 ;")
    public Result listPage(Page<UserVo> page, UserQuery userQuery, CommonQuery commonQuery) {
        QueryWrapper<SysUser> autoQueryWrapper = QueryGenerator.initQueryWrapper(userQuery, commonQuery);
        return Res.ok(sysUserService.getUserWithRolePage(page, autoQueryWrapper));
    }

    /**
     * 获取登录的用户信息  用户登陆
     */
    @GetMapping("/info")
    @ApiOperation(value = "查询当前用户信息")
    public Result<UserInfo> info() {
        Long currentUserId = SecurityUtils.getUser().getId();
        SysUser user = sysUserService.getById(currentUserId);
        return Res.ok(sysUserService.findUserInfo(user));
    }


    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    @ApiOperation(value = "根据用户id查询用户信息")
    public Result<UserInfo> info(@ApiParam(value = "用户id") @PathVariable("userId") Long userId) {
        SysUser user = sysUserService.getById(userId);
        //获取用户所属的角色列表
        UserInfo userInfo = sysUserService.findUserInfo(user);
        return Res.ok(userInfo);
    }

    /**
     * 保存用户
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增用户")
    @PreAuthorize("@pms.hasPermission('sys:user:save')")
    public Result<Boolean> save(@RequestBody UserDto user) {
        return Res.ok(sysUserService.saveUser(user));
    }

    /**
     * 修改用户
     */
    @PostMapping("/update")
    @PreAuthorize("@pms.hasPermission('sys:user:update')")
    @ApiOperation(value = "更新用户")
    public Result<Boolean> update(@RequestBody UserDto user) {
        return Res.ok(sysUserService.updateUserById(user));
    }

    /**
     * 删除用户
     */
    @GetMapping("/delete/{userId}")
    @PreAuthorize("@pms.hasPermission('sys:user:del')")
    @ApiOperation(value = "删除用户")
    public Result<Boolean> delete(@ApiParam(value = "用户id") @PathVariable("userId") Long userId) {
        Long currentUserId = SecurityUtils.getUser().getId();
        if (userId.equals(SUPER_ADMIN)) {
            return Res.error("不能删除管理员");
        }
        if (userId.equals(currentUserId)) {
            return Res.error("当前用户不能删除");
        }
        return Res.ok(sysUserService.deleteUserById(userId));
    }


    /**
     * @param userForm
     * @return
     */
    @PostMapping("/edit")
    @ApiOperation(value = "用户信息个人信息")
    public Result edit(@RequestBody UserForm userForm) {
        UserDetail userDetail = SecurityUtils.getUser();
        SysUser temp = new SysUser();
        temp.setUserId(userDetail.getId());
        temp.setPhone(userForm.getPhone());
        temp.setUsername(userForm.getUsername());
        sysUserService.update(temp, new LambdaUpdateWrapper<SysUser>().eq(SysUser::getUserId, userDetail.getId()));
        return Res.ok();
    }

    /**
     * 修改用户头像
     *
     * @return
     */
    @PutMapping("/updateAvatar")
    @ApiOperation(value = "修改用户头像")
    public Result updateAvatar(@RequestParam("url") String url) {
        Long userId = SecurityUtils.getUser().getId();
        sysUserService.update(new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getAvatar, url)
                .eq(SysUser::getUserId, userId)
        );
        return Res.ok("更新成功");
    }

    /**
     * 更新当前用户密码
     *
     * @param userForm
     * @return
     */
    @PutMapping("/updatePassowrd")
    @ApiOperation(value = "当前登录用户修改密码")
    public Result updatePassword(@RequestBody UserForm userForm) {
        Long userId = SecurityUtils.getUser().getId();
        sysUserService.updatePassword(userId, userForm.getPassword(), userForm.getNewpass());
        return Res.ok("修改成功");
    }

    /**
     * 查询当前鞥路账户绑定情况
     *
     * @return
     */
    @GetMapping("/binding")
    @ApiOperation(value = "用户绑定情况")
    public Result listBind() {

        Long userId = SecurityUtils.getUser().getId();
        SysUser user = sysUserService.getById(userId);

        Map<String, Boolean> map = MapUtil.newHashMap();
        // 码云是否绑定
        map.put("gitee", StrUtil.isNotBlank(user.getGiteeLogin()));
        // 微信是否绑定
        map.put("wechat", StrUtil.isNotBlank(user.getWxOpenid()));
        // 钉钉是否绑定
        map.put("ding", StrUtil.isNotBlank(user.getDingId()));

        map.put("wework", StrUtil.isNotBlank(user.getWework()));
        return Res.ok(map);
    }

    /**
     * 用户下拉框
     *
     * @return 用户list
     */
    @GetMapping("/dropDown")
    public Result<List<DropDown>> select() {
        List<DropDown> list = sysUserService.dropDown().stream()
                .map(item -> new DropDown().setLabel(item.getUsername()).setValue(item.getUserId() + ""))
                .collect(Collectors.toList());
        return Res.ok(list);
    }
}

